package com.generator.utils;

import com.generator.config.JDBCConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.*;

/**
 * 〈database util〉
 *
 * @author xsh
 * @create 2018/9/17
 * @since 1.0.0
 */
@Component
public class DBUtil {

    @Autowired
    JDBCConfiguration configuration;

    public   Connection  getConnection() {
        try{
           return DriverManager.getConnection(configuration.getUrl(),configuration.getUsername(),configuration.getPassword());
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }


    public PreparedStatement getStatement(Connection connection ,String  sql){
        try{
            if (connection ==null){
                connection =getConnection();
            }
            return connection.prepareStatement(sql);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }


    public  void  release(Connection connection , PreparedStatement statement , ResultSet resultSet){
        try{
            if (connection!=null){
                connection.close();
            }
            if (statement!=null){
                statement.close();
            }
            if (resultSet!=null){
                resultSet.close();
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }


}